<?php
/**
 * Framework_Util_SearchParams
 *
 * 
 *
 * @author Application Support Group
 * @copyright University of Georgia
 * @package BAMF
*/

class Framework_Util_SearchParams {

/**
 * Framework_Util_SearchParams::create()
 *
 * Splits a search string into keywords
 *
 * @param		string $searchVal_0 string of keywords.
 *
 * @return		array
 *
 * @package		BAMF
 * 
 */
	public static function explodeKeywords($searchVal_0) {
		$keywords = array() ;
		// pull out any quoted strings and build those pieces of the search string
		$pattern = '/"(.*?)"/' ;
		preg_match_all($pattern, $searchVal_0, $matches, PREG_OFFSET_CAPTURE);
	
		$queryRemainder = $searchVal_0 ;
		for ($i = count($matches[0]); $i > 0; $i--) {
			//get offset and value of quoted string
			$strIndex = $matches[0][$i-1][1] ;
			//add quoted string to $keywords
			$keywords[] = $matches[1][$i-1][0] ;
			//remove quoted string from oringinal query
			$queryRemainder = substr_replace( $queryRemainder, '', $strIndex, strlen($matches[0][$i-1][0]) ) ;
		}
		
		//add everything leftover to $keywords
		$remainderArr = explode(" ", trim($queryRemainder)) ;
		
		foreach ($remainderArr as $remainder) {
			if (!empty( $remainder )) $keywords[] = $remainder ;
		}
		
		return $keywords;
	}

/**
 * Framework_Util_SearchParams::create()
 *
 * Create a Framework_DB_DaoCollectionParameters object based on search
 * parameters coming from the searchBar.tpl file, the node schema, and any base
 * parameters.
 *
 * @param		array $schema Node schema as parsed from the ini file.
 * @param		string $baseWhere Base WHERE clause to use in the collection parameters.
 * @param		boolean $keywordSearch Set to true to perform a keyword search.
 *
 * @return		Framework_DB_DaoCollectionParameters
 *
 * @package		BAMF
 * 
 */

	public static function create( $schema, $baseWhere = '', $keywordSearch = false, $collectionNodeType ) {

		$searchParams = array() ;	
		$searchStr = '' ;
		$searchValues = array();
		$i = 0;
		if (!empty($_POST[ SBAR_KEY_SUBMIT ]) && $_POST[ SBAR_KEY_SUBMIT ] == SBAR_VAL_SUBMIT ) {
			if(!is_array($_POST[SBAR_KEY_SEARCH_COLUMN])) {
				$_POST[SBAR_KEY_SEARCH_COLUMN] = array($_POST[SBAR_KEY_SEARCH_COLUMN]);
			}
			if(!is_array($_POST[SBAR_KEY_SEARCH_0])) {
				$_POST[SBAR_KEY_SEARCH_0] = array($_POST[SBAR_KEY_SEARCH_0]);
			}
			if(!is_array($_POST[SBAR_KEY_SEARCH_1])) {
				$_POST[SBAR_KEY_SEARCH_1] = array($_POST[SBAR_KEY_SEARCH_1]);
			}
			while(isset($_POST[SBAR_KEY_SEARCH_COLUMN]) && 
					isset($_POST[SBAR_KEY_SEARCH_COLUMN][$i]) &&
					$_POST[SBAR_KEY_SEARCH_COLUMN][$i]) {
				if($i > 0) {
						if($_POST["search_conjunction"][$i] == "AND" || 
							$_POST["search_conjunction"][$i] == "OR" ) {
						$searchStr .= ") {$_POST['search_conjunction'][$i]} (" ;
					} else {
						break;
					}
				} else {
					$searchStr .= '(' ;
				}
				$searchCol = $_POST[ SBAR_KEY_SEARCH_COLUMN ][$i];
	
				//This appears to be the only string manipulation we need to do anymore, and if we don't slashes are just ignored. Thanks, MDB2!		
				$searchVal_0 = str_replace('\\', '\\\\', $_POST[ SBAR_KEY_SEARCH_0 ][$i]);
				$searchVal_1 = str_replace('\\', '\\\\', $_POST[ SBAR_KEY_SEARCH_1 ][$i]);
	
				
				if(array_key_exists($searchCol, $schema['field_definitions'])) {
					switch ($schema["field_definitions"][$searchCol]) {
						case DB_DATATYPE_DATETIME:
							if (empty($searchVal_0)) $searchVal_0 = date("Y-m-d",strtotime("1990-01-01"));
							if (empty($searchVal_1)) $searchVal_1 = date("Y-m-d");
							
							
							$searchVal_1 .= " 23:59:59";
							$searchStr .= "{$searchCol} > ? AND {$searchCol} <= ?";
							$searchValues[] = $searchVal_0;
							$searchValues[] = $searchVal_1;
							break;
							
						case DB_DATATYPE_FLOAT:
						case DB_DATATYPE_INTEGER:
						case DB_DATATYPE_KEY:
							if (!Framework_Util_DataCheck::emptyNotZero($searchVal_0)) {
	
								$searchStr .= "$searchCol = ?";
								$searchValues[] = $searchVal_0;
							}
							break;
						case DB_DATATYPE_VIRTUAL:
							$getWhereStr = call_user_func(array($collectionNodeType, 'getWhere'), $searchCol, $searchVal_0, $keywordSearch);
							if(is_array($getWhereStr) && 
									array_key_exists('where',$getWhereStr) && 
									array_key_exists('values', $getWhereStr)) {
								$searchValues = array_merge($searchValues, $getWhereStr['values']);
								$searchStr .= $getWhereStr['where'];
							} elseif(is_string($getWhereStr)) {
								$searchStr .= $getWhereStr;
							} else {
								$searchStr .= '1 = 1';
							}
							break;
						default:
							if (empty($searchVal_0)) $searchVal_0 = "%" ;
		
							if ($keywordSearch) {
									$keywords = Framework_Util_SearchParams::explodeKeywords($searchVal_0);
									
								$searchStr .= "1 = 1 " ;
								foreach ($keywords as $keyword) {
									$searchStr .= "AND UPPER({$searchCol}) LIKE ? ";
									$searchValues[] = "%".strtoupper($keyword)."%";
								}
							} else {
								$searchStr .= "UPPER(".$searchCol.") LIKE ? ";
								$searchValues[] = strtoupper($searchVal_0);					
							}
							break;
					}
				}
				$i++;
			}
		}
		if($searchStr != '') {
			$searchStr .= ')' ;
		}
		
		if (!empty($searchStr) && $searchStr != '()') {
			if (!empty($baseWhere)) {
				if(is_array($baseWhere)) {
					$searchParams[] = "($searchStr) AND ({$baseWhere['where']})";
					$searchValues = array_merge($searchValues, $baseWhere['values']);
				} else { 
					$searchParams[] = "($searchStr) AND ($baseWhere)";
				}
			} else {
				$searchParams[] = $searchStr ;
			}
		} else {
			if (!empty( $baseWhere )) {
				if(is_array($baseWhere)) {
					$searchParams[] = $baseWhere['where'];
					$searchValues = $baseWhere['values'];
				} else {
					$searchParams[] = $baseWhere ;
				}
			}
		}
		

		if (count($searchParams) > 0 ) {
			$collParams = new Framework_DB_DaoParameters( array( "where" => $searchParams, "values" => $searchValues )) ;
		} else {
			$collParams = new Framework_DB_DaoParameters() ;
		}

		if (isset( $_POST[ SBAR_KEY_SEARCH_COLUMN ] ) && isset( $_POST[ SBAR_KEY_SEARCH_0 ] ) && isset( $_POST[ SBAR_KEY_SEARCH_1 ] )) {
			if( isset( $_POST[ SBAR_KEY_SEARCH_1 ] )) {
				$collParams->rawSearchParams = serialize(array(
						"search_column" => $_POST[ SBAR_KEY_SEARCH_COLUMN ], 
						"search_value_0" => $_POST[ SBAR_KEY_SEARCH_0 ], 
						"search_value_1" => $_POST[ SBAR_KEY_SEARCH_1 ],
						"search_conjunction" => (array_key_exists('search_conjunction', $_POST) ?
									$_POST["search_conjunction"] : array())));
			} else {
				$collParams->rawSearchParams = serialize(array(
						"search_column" => $_POST[ SBAR_KEY_SEARCH_COLUMN ], 
						"search_value_0" => $_POST[ SBAR_KEY_SEARCH_0 ], 
						"search_value_1" => '',
						"search_conjunction" => (array_key_exists('search_conjunction', $_POST) ?
									$_POST["search_conjunction"] : array())));
			}
		}
		
		return $collParams ;
	
	}



}


?>